//
//  SYLJRefreshControl.swift
//  Weibo10
//
//  Created by 刘俊 on 15/10/23.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

/// 刷新控件的偏移量
private let RefreshControlOffset: CGFloat = -60
/// 自定义刷新控件 - 负责处理刷新逻辑
class SYLJRefreshControl: UIRefreshControl {

    //MARK: - KVO的监听处理
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
        // 判断是否在刷新控件
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < RefreshControlOffset && !refreshView.rotateFlag {
            
//            print("转上去")
            refreshView.rotateFlag = true
//            refreshView.rolateAnim()
        }else if frame.origin.y > RefreshControlOffset && refreshView.rotateFlag {
//            print("转下来")
            refreshView.rotateFlag = false
//            refreshView.rolateAnim()
        }
        
    }
    // MARK: - 重写父类停止刷新和开始刷新
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAmimation()
    }
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    /// 构造方法
    override init() {
        super.init()
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 设置UI
    private func setupUI() {
        // 隐藏转轮
        tintColor = UIColor.clearColor()
        // 添加控件
        addSubview(refreshView)
        // 添加约束
        //对于刷新视图的自动布局必须要设置大小的自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        /// KVO监听刷新属性的位置变化
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    deinit {
        // 删除 KVO 监听方法
        self.removeObserver(self, forKeyPath: "frame")
    }
    /// 懒加载添加控件
    private lazy var refreshView: RefreshView = RefreshView.refreshView()
}

//MARK: - 刷新视图
class RefreshView: UIView {
    
    @IBOutlet weak var refreshImage: UIImageView!
    @IBOutlet weak var LoadingVIew: UIView!
    @IBOutlet weak var LoadingImage: UIImageView!
    private  var rotateFlag = false {
        didSet {
            rolateAnim()
        }
    }
    
    /// 从xib加载视图
    class func refreshView() -> RefreshView {
        let nib = UINib(nibName: "RefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! RefreshView
    }
    
    /// 旋转图标动画
    private func rolateAnim() {
        UIView.animateWithDuration(0.25) { () -> Void in
            
            var angle: CGFloat = CGFloat(M_PI)
            angle += self.rotateFlag ? -0.000001 : 0.000001
            self.refreshImage.transform = CGAffineTransformRotate(self.refreshImage.transform, CGFloat(angle))
        }
    }
    /// 播放加载动画
    private func startAnimation() {
        LoadingVIew.hidden = false
        // 判断动画是否已经被添加
        let key = "transform.rotation"
        if LoadingImage.layer.animationForKey(key) != nil {
            return
        }
        
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.duration = 0.5
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false
        
        LoadingImage.layer.addAnimation(anim, forKey: key)
    }
    /// 停止播放动画
    private func stopAmimation() {
        LoadingVIew.hidden = true
        
        LoadingImage.layer.removeAllAnimations()
    }
    
}